﻿using System;
using System.Collections.Generic;
using BusinessLogic.Connectivity.Entities;
using BusinessLogic.Managers.Processing;
using BusinessLogic.Mappers;
using BusinessLogic.Mappers.DocumentEnvelopes;
using DataAccess.Services;

namespace BusinessLogic.Managers
{
	public static class ProcessingManager
	{
		public static void ProcessReceivedEnvelopes()
		{
			using (IServiceManager serviceManager = new ServiceManager())
			{
				IDocumentEnvelopeMapper mapper = MapperFactory.GetDocumentEnvelopeMapper(serviceManager);
				
				IEnumerable<DocumentEnvelope> envelopes = mapper.SelectReceivedEnvelopes();

				foreach (DocumentEnvelope envelope in envelopes)
				{
					DocumentEnvelope envelopeCopy = envelope;

					try
					{
						ProcessEnvelope(serviceManager, envelope, envelopeCopy);
					}
					catch (Exception e)
					{
						// TODO: add logging logic.
						// do nothing for now...
					}
					finally
					{
						try
						{
							mapper.Update(envelope);
						}
						catch
						{
							// doing nothing....
						}
					}
				}
			}
		}

		private static void ProcessEnvelope(IServiceManager serviceManager, DocumentEnvelope envelope, DocumentEnvelope envelopeCopy)
		{
			new ProcessingExceptionCatcher().Execute((a1, a2) =>
			                                         	{
			                                         		IDocumentProcessor processor =
			                                         			DocumentProcessingFactory.GetProcessor(envelopeCopy.DocumentType);

			                                         		envelope.RejectionReason = string.Empty;

			                                         		processor.Process(envelopeCopy, serviceManager);
			                                         	},
			                                         null, serviceManager, envelope);
		}
	}
}
